/**
 * 
 */
package org.meruvian.yama.demo.dao;

import javax.persistence.TypedQuery;

import org.meruvian.yama.demo.entity.Person;
import org.meruvian.yama.persistence.EntityListWrapper;
import org.meruvian.yama.persistence.LogInformation.StatusFlag;
import org.meruvian.yama.persistence.access.PersistenceDAO;
import org.meruvian.yama.persistence.utils.PagingUtils;
import org.springframework.stereotype.Repository;

/**
 * @author Dian Aditya
 * 
 */
@Repository
public class PersonDao extends PersistenceDAO<Person> {

	protected String convertNullToEmptyString(String string) {
		if (string == null) {
			return "";
		}

		return string.trim();
	}

	public EntityListWrapper<Person> getByExample(Person person, int max,
			int page) {
		EntityListWrapper<Person> persons = new EntityListWrapper<Person>();

		String criteria = "(p.firstName LIKE ? AND p.lastName LIKE ? AND p.middleName LIKE ?) AND p.logInformation.statusFlag = ?";
		Object[] parameters = {
				"%" + convertNullToEmptyString(person.getFirstName()) + "%",
				"%" + convertNullToEmptyString(person.getMiddleName()) + "%",
				"%" + convertNullToEmptyString(person.getLastName()) + "%",
				StatusFlag.ACTIVE };

		long rowcount = createQuery(Long.class, "COUNT(p)", "p", criteria,
				parameters).getSingleResult();

		persons.setCurrentPage(page);
		persons.setLimit(max);
		persons.setRowCount(rowcount);

		TypedQuery<Person> query = createQuery(entityClass, "p", "p", criteria,
				parameters);
		if (max > 0) {
			persons.setTotalPage(PagingUtils.getTotalPage(rowcount, max));
			query.setMaxResults(max);
			query.setFirstResult(max * page);
		}

		persons.setEntityList(query.getResultList());

		return persons;
	}
}
